package io.zerous.zexgraph;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;

import java.io.File;

public class EditorActivity extends AppCompatActivity {
    private final String UNTITLED = "untitled.lua";

    private boolean fileChanged = true;
    private String currentFileName = "untitled.lua";

    boolean result;

    EditText wEditor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        wEditor = findViewById(R.id.mainEditor);

        wEditor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                fileChanged = true;
                getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
            }
        });

        if (savedInstanceState != null) {
            currentFileName = savedInstanceState.getString("currentFileName");
            wEditor.setText(FileUtils.readTextFile(EditorActivity.this, currentFileName));
            fileChanged = false;
        }

        getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
    }

    @Override
    protected void onResume() {
        super.onResume();

        loadCurrentFile();
    }

    private void loadCurrentFile() {
        Intent intent = getIntent();
        String theFile = intent.getStringExtra("cFileName");
        if (!theFile.isEmpty()) {
            currentFileName = theFile;

            wEditor.setText(FileUtils.readTextFile(EditorActivity.this, currentFileName));
            fileChanged = false;
            getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
        } else {
            currentFileName = UNTITLED;
            wEditor.setText("");
            fileChanged = true;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_editor, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            turnToMainActivity();
            return true;
        }
        return false;
    }

    private void turnToMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        if (!UNTITLED.equals(currentFileName)) intent.putExtra("cFileName", currentFileName);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        if (!UNTITLED.equals(currentFileName))
            outState.putString("currentFileName", currentFileName);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!UNTITLED.equals(currentFileName)) {
            String src = wEditor.getEditableText().toString();

            FileUtils.saveTextFile(EditorActivity.this, currentFileName, src);
            fileChanged = false;
            getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState != null) {
            currentFileName = savedInstanceState.getString("currentFileName");
            wEditor.setText(FileUtils.readTextFile(EditorActivity.this, currentFileName));
            fileChanged = false;
        }

        getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
    }

    public void openFile(MenuItem item) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle(R.string.select_file);
        final ListAdapter listAdapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_list_item_1,
                FileUtils.getSrcFileNames(this)
        );

        b.setAdapter(listAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                currentFileName = (String)listAdapter.getItem(which);

                wEditor.setText(FileUtils.readTextFile(EditorActivity.this, currentFileName));
                fileChanged = false;
                getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
            }
        });

        b.show();
    }

    public void saveFile(MenuItem item) {
        if (!fileChanged) return;

        if (UNTITLED.equals(currentFileName)) {
            openSaveFileAs();
        } else {
            String src = wEditor.getEditableText().toString();

            FileUtils.saveTextFile(EditorActivity.this, currentFileName, src);
            fileChanged = false;
            getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
        }

    }


    public void deleteScript(MenuItem item) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle(R.string.delete_dialog_title);
        b.setMessage("你正打算删除的是：" + currentFileName + "\n（删了可就回不来了~！）");
        b.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FileUtils.deleteFile(EditorActivity.this, currentFileName);

                currentFileName = UNTITLED;
                wEditor.setText("");
                fileChanged = true;
            }
        });
        b.setNegativeButton(android.R.string.no, null);
        b.show();
    }

    public void newFile(MenuItem item) {
        if (fileChanged && !UNTITLED.equals(currentFileName)) {
            if (!makeSureNotToSave()) {
                return;
            }
        }

        currentFileName = UNTITLED;
        wEditor.setText("");
        fileChanged = true;
    }

    public void saveFileAs(MenuItem item) {
        openSaveFileAs();
    }

    private boolean makeSureNotToSave() {
        result = false;
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Sure?");
        b.setMessage("The file will not be saved.");
        b.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                result = true;
            }
        });
        b.setNegativeButton(android.R.string.no, null);
        b.show();

        return result;
    }

    private void openSaveFileAs() {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        final EditText sFileName = new EditText(this);
        if (!"untitled.lua".equals(currentFileName)) {
            sFileName.setText(currentFileName);
        } else {
            sFileName.setText(".lua");
            sFileName.setSelection(0);

        }
        b.setTitle(R.string.script_save);
        b.setView(sFileName);
        b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                currentFileName = sFileName.getEditableText().toString();
                String src = wEditor.getEditableText().toString();

                FileUtils.saveTextFile(EditorActivity.this, currentFileName, src);
                fileChanged = false;
                getSupportActionBar().setSubtitle(currentFileName + (fileChanged ? "*" : ""));
            }
        });
        AlertDialog alertDialog = b.create();
        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                InputMethodManager imm = (InputMethodManager)EditorActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });

        alertDialog.show();
    }

    private String[] getSrcFileNames() {
        File[] fList = getFilesDir().listFiles();
        String[] list = new String[fList.length];

        for (int i = 0;i < fList.length;++i) {
            list[i] = fList[i].getName();
        }
        return list;
    }
}
